import React, { useState, useEffect } from "react";
import { Table, Button, Card, Divider, Pagination, Modal, message, Popconfirm } from "antd";
import {
  rolesAdd,
  rolesUpdate,
  rolesDel,
  rolesPage,
  roleSetPermits
} from "@/api/roles";
import AddForm from "./addForm";
import PermitsList from "./permitsList";
export default function Roles() {
  const [rolesList, setRolesList] = useState([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [rolesInfo, setRolesInfo] = useState({})
  const [roleId, setRoleId] = useState('')
  const [authIds, setAuthIds] = useState('')
  const [isPermitVisible, setIsPermitVisible] = useState(false)

  // 初始化表头
  const columns = [
    {
      title: "序号",
      width: 60,
      align: 'center',
      render: (value, row, index) => {
        return `${index + 1}`
      }
    },
    {
      title: "名称",
      dataIndex: "roleName",
      key: "roleName",
      width: 120
    },
    {
      title: "描述",
      dataIndex: "roleDesc",
      key: "roleDesc"
    },
    {
      title: "操作",
      dataIndex: "Operation",
      key: "Operation",
      width: 300,
      // responsive: ["lg"],
      render: (value, row, index) => {
        return (
          <div>
            <Button
              type='primary'
              size='small'
              onClick={() => showRolePermits(row)}
            >
              分配权限
            </Button>
            <Divider type='vertical' />
            <Button
              size='small'
              onClick={() => addFrom(row)}
            >
              修改
            </Button>
            <Divider type='vertical' />
            <Popconfirm
              title="您确定要删除此项吗？"
              okText="是"
              cancelText="否"
              onConfirm={() => delBtn(row._id)}
            >
              <Button
                type='primary'
                size='small'
                danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      }
    }
  ];
  // 获取角色列表
  const getRolesList = () => {
    setLoading(true)
    rolesPage({ pageNo, pageSize })
      .then(res => {
        setRolesList(res.data.data)
        setTotal(res.data.total)
        setLoading(false)
      })
      .catch(err => {
        setLoading(false)
      });
  };
  // 配置权限
  const showRolePermits = row => {
    setRoleId(row.roleId)
    setAuthIds(row.authIds)
    setIsPermitVisible(true)
  };
  // 分页事件
  const paginationChange = (pageNo, pageSize) => {
    setPageNo(pageNo)
    setPageSize(pageSize)
    getRolesList()
  };
  // 添加角色
  const addFrom = row => {
    if (row) {
      // 编辑
      setRoleId(row.roleId)
      setRolesInfo(row)
      setIsModalVisible(true)
    } else {
      // 新增
      setRoleId('')
      setRolesInfo({})
      setIsModalVisible(true)
    }
  };

  const handleCancel = () => {
    setRoleId('')
    setRolesInfo({})
    setIsModalVisible(false)
  };

  const delBtn = _id => {
    rolesDel({ _id })
      .then(res => {
        if (res.data.code === 200) {
          getRolesList()
          return message.success("删除成功")
        }
        message.error(res.data.msg)
      })
  }

  const handlePermitCancel = () => {
    setIsPermitVisible(false)
  };

  useEffect(() => {
    getRolesList();
  }, [])// eslint-disable-line react-hooks/exhaustive-deps

  const onOk = val => {
    if (roleId) {
      rolesUpdate({ roleId: roleId, ...val }).then(res => {
        if (res.data.code === 200) {
          getRolesList();
          message.success("修改成功");
        } else {
          message.error(res.data.msg);
        }
      });
    } else {
      rolesAdd({ ...val }).then(res => {
        if (res.data.code === 200) {
          getRolesList();
          message.success("添加成功");
        } else {
          message.error(res.data.msg);
        }
      });
    }
    handleCancel()
  };

  const permitOk = authIds => {
    roleSetPermits({ roleId: roleId, authIds: authIds }).then(res => {
      if (res.data.code === 200) {
        getRolesList();
        message.success("修改成功");
      } else {
        message.error(res.data.msg);
      }
    });
    setRoleId('')
    setIsPermitVisible(false)
  }

  const title = "角色分类列表";
  const extra = <Button onClick={addFrom}>添加</Button>;

  return (
    <Card title={title} extra={extra} className="cardBox">
      <Table
        className="tableBox"
        rowKey='roleId'
        loading={loading}
        columns={columns}
        dataSource={rolesList}
        pagination={false}
      />
      <br />
      {total ? (
        <Pagination
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={total => `共 ${total} 条`}
          onChange={paginationChange}
        />
      ) : (
        ""
      )}
      <Modal
        title='添加角色'
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <AddForm
          onOk={onOk}
          onCancel={handleCancel}
          rolesInfo={rolesInfo}
        />
      </Modal>
      <Modal
        title='配置权限'
        visible={isPermitVisible}
        onCancel={handlePermitCancel}
        footer={null}
      >
        <PermitsList
          onOk={permitOk}
          onCancel={handlePermitCancel}
          authIds={authIds}
        />
      </Modal>
    </Card>
  );
}
